<template>
	<div class="div1">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		</el-breadcrumb>
	</div>
	<div>
		<div class="div2">
			<span class="spanTop">咨询师名称</span>
			<el-input size="large" v-model="searchName" style="width: 240px" placeholder="请输入咨询师名称" clearable
				@clear="query" />
			<span class="spanTop">咨询师等级</span>
			<el-select clearable @clear="searchLevelId=''" v-model="searchLevelId" placeholder="请选择咨询师等级" size="large" style="width: 240px">
				<el-option v-for="item in AllCounselorLevel" :key="item.id" :value="item.id" :label="item.levelName" />
			</el-select>
			<span class="spanTop">地址</span>
			<el-input size="large" v-model="searchAddress" style="width: 240px" placeholder="请输入地址" clearable
				@clear="query" />
			<span class="spanTop">手机号</span>
			<el-input size="large" v-model="searchPhone" style="width: 240px" placeholder="请输入手机号" clearable
				@clear="query" />
		</div>
		<el-button @click="query" type="primary" size="large" class="bt1">搜索</el-button>
		<el-button type="primary" @click="createOrUpdate('')" size="large" class="bt1">新增咨询师</el-button>
		<el-button type="danger" size="large" class="bt1" @click="removeAll">批量删除</el-button>

		<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" />
			<el-table-column fixed prop="id" label="ID" width="50" />
			<el-table-column prop="name" label="咨询师名称" />
			<el-table-column prop="gender" label="性别" />
			<el-table-column prop="level.levelName" label="咨询师等级" />
			<el-table-column prop="conAndExper" label="擅长领域">
				<template #default="{row}">
					<span v-for="item in row.conAndExper" :key="item.id">
						{{ item.expertiseFiled.fieldName }}
						<br />
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="mobile" label="手机号" />
			<el-table-column prop="email" label="邮箱" />

			<el-table-column prop="avatarUrl" label="头像">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="getOssImageUrl(scope.row.avatarUrl)" />
				</template>
			</el-table-column>


			<el-table-column label="证书图片">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="getOssImageUrl(scope.row.certificateUrl)" />
				</template>
			</el-table-column>

			<el-table-column prop="address" label="所属地址" />
			<el-table-column prop="introduction" label="咨询师简介" />
			<el-table-column label="职位" width="100">
				<template #default="scope">
					<div class="counselorPostsOne" v-if="scope.row.position === '咨询师'">咨询师</div>
					<div class="counselorPostsTwo" v-else>心理导师</div>
				</template>
			</el-table-column>

			<el-table-column fixed="right" label="操作" width="180">
				<template #default="scope">
					<el-button type="primary" @click="createOrUpdate(scope.row)">编辑</el-button>
					<el-button type="danger" @click="remove(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog v-model="dialogFormVisible" :title="form.id.length==0?'新增咨询师':'编辑咨询师'" width="800"
			style="margin-bottom: 60px;" @close="handleClose">
			<el-form>
				<el-form-item label="咨询师名称" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.name" autocomplete="off" placeholder="请输入咨询师名称" />
				</el-form-item>
				<el-form-item label="咨询师性别" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.gender" placeholder="请选择咨询师性别" size="large" style="width: 240px">
						<el-option value="男" label="男" />
						<el-option value="女" label="女" />
					</el-select>
				</el-form-item>
				<el-form-item label="咨询师等级" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.levelId" placeholder="请选择咨询师等级" size="large" style="width: 240px">
						<el-option v-for="item in AllCounselorLevel" :key="item.id" :value="item.id"
							:label="item.levelName" />
					</el-select>
				</el-form-item>
				<el-form-item label="擅长领域" :label-width="formLabelWidth">
					<el-select v-model="form.fieldIds" multiple placeholder="请选择" size="large" style="width: 240px">
						<el-option v-for="item in AllExpertiseFields" :key="item.id" :value="item.id"
							:label="item.fieldName" />
					</el-select>
				</el-form-item>
				<el-form-item label="手机号" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.mobile" autocomplete="off" placeholder="请输入手机号" />
				</el-form-item>
				<el-form-item label="邮箱" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.email" autocomplete="off" placeholder="请输入邮箱" />
				</el-form-item>

				<el-form-item label="头像" :label-width="formLabelWidth">
					<el-upload :action="getUploadUrl()" list-type="picture-card"
						:on-success="handleAvatarSuccess" :limit="1" :on-preview="handleAvatarPreview"
						:file-list="fileList" :on-remove="handleAvatarRemove">
						<el-icon
							style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<el-dialog v-model="avatarDialogVisible">
						<img w-full :src="avatarDialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>

				<el-form-item label="证书图片" :label-width="formLabelWidth">
					<el-upload :action="getUploadUrl()" list-type="picture-card"
						:on-success="handleCertificateSuccess" :limit="1" :on-preview="handleCertificatePreview"
						:file-list="certificateFileList" :on-remove="handleCertificateRemove">
						<el-icon
							style="width: 128px; height: 128px;border: 1px dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
							<Plus />
						</el-icon>
					</el-upload>
					<el-dialog v-model="certificateDialogVisible">
						<img w-full :src="certificateDialogImageUrl" alt="Preview Image" />
					</el-dialog>
				</el-form-item>

				<el-form-item label="所属地址" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.address" autocomplete="off" placeholder="请上传所属地址" />
				</el-form-item>
				<el-form-item label="咨询师简介" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.introduction" autocomplete="off" placeholder="请上传咨询师简介" />
				</el-form-item>
				<el-form-item label="咨询师分类" :label-width="formLabelWidth" style="clear: left;">
					<el-select v-model="form.position" placeholder="请选择咨询师分类" size="large" style="width: 240px">
						<el-option value="咨询师" label="咨询师" />
						<el-option value="心理导师" label="心理导师" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button @click="dialogFormVisible = false,add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total=" total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" v-if="total !=0" />
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		computed,
		watch
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		getCurrentInstance
	} from 'vue';
	import { OSS_CONFIG, getOssImageUrl,getUploadUrl  } from '../../util/ossConfig';

	const axios = getCurrentInstance().appContext.config.globalProperties.axios
	const tableData = ref([])
	const currentPage = ref(1) // 当前页
	const pageSize = ref(10) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const searchName = ref('')
	const searchCounselorLevelName = ref('')
	const searchAddress = ref('')
	const searchPhone = ref('')
	const searchLevelId = ref('');
	const AllExpertiseFields = ref([]);

	const form = ref({
		address: "",
		gender:"",
		certificateUrl: "",
		email: "",
		avatarUrl: "",
		levelId: "",
		name: "",
		mobile: "",
		position: "",
		introduction: "",
		id: "",
		fieldName: "",
		fieldIds: [],
		del: 0
	})

	const dialogFormVisible = ref(false)
	const formLabelWidth = '100px'
	const AllCounselorLevel = ref([])

	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])
	const certificateFileList = ref([])
	const avatarDialogVisible = ref(false)
	const avatarDialogImageUrl = ref('')
	const certificateDialogVisible = ref(false)
	const certificateDialogImageUrl = ref('')

	const handleAvatarPreview = (file) => {
		avatarDialogImageUrl.value = file.url
		avatarDialogVisible.value = true
	}
	const handleCertificatePreview = (file) => {
		certificateDialogImageUrl.value = file.url
		certificateDialogVisible.value = true
	}
	const handleAvatarSuccess = (res, file) => {
		form.value.avatarUrl = res.data; // 保存图片路径
		fileList.value = [{
			name: '头像',
			url: getOssImageUrl(res.data)
		}]
	}
	const handleCertificateSuccess = (res, file) => {
		form.value.certificateUrl = res.data; // 保存相对路径到表单
		certificateFileList.value = [{
			name: '证书',
			url: getOssImageUrl(res.data) // 拼接完整地址用于预览
		}]
	}

	const handleAvatarRemove = () => {
		form.value.avatarUrl = '';
		fileList.value = [];
	}
	const handleCertificateRemove = () => {
		form.value.certificateUrl = '';
		certificateFileList.value = [];
	}

	const getAllCounselorLevel = () => {
		axios.get('level', ).then((resp) => {
			console.log(resp.data);
			AllCounselorLevel.value = resp.data
		});
	}

	function query() {
		axios.get(
			`/consultant/page?name=${searchName.value}&levelId=${searchLevelId.value}&address=${searchAddress.value}&mobile=${searchPhone.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			tableData.value = resp.data.list;
			total.value = resp.data.total
			console.log(resp.data);
			console.log('tableData', tableData.value);
		})
	}
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const handleClose = () => {
		form.value = {
			address: "",
			gender:"",
			certificateUrl: "",
			counselorEmail: "",
			avatarUrl: "",
			levelId: 1,
			name: "",
			mobile: "",
			position: "",
			introduction: "",
			fieldName: "",
			id: "",
		}
	}
	const createOrUpdate = (row) => {
		dialogFormVisible.value = true
		if (row != '') {
			axios.get(`consultant/${row.id}`).then((resp) => {
				form.value = resp.data
				// 头像回显 - 拼接完整地址
				if (resp.data.avatarUrl) {
					fileList.value = [{
						name: '头像',
						url: getOssImageUrl(resp.data.avatarUrl) // 拼接完整地址
					}]
				} else {
					fileList.value = []
				}
				console.log('头像fileList', fileList.value)
				// 证书回显 - 拼接完整地址
				if (resp.data.certificateUrl) {
					certificateFileList.value = [{
						name: '证书',
						url: getOssImageUrl(resp.data.certificateUrl) // 拼接完整地址
					}]
				} else {
					certificateFileList.value = []
				}
				// 擅长领域
				if (resp.data.conAndExper && resp.data.conAndExper.length > 0) {
					form.value.fieldIds = resp.data.conAndExper.map(item => item.fieldId)
				} else {
					form.value.fieldIds = []
				}
			})
		} else {
			form.value.fieldIds = []
			fileList.value = []
			certificateFileList.value = []
		}
	}
	const getAllExpertiseFields = () => {
		axios.get('expertiseFiled').then(resp => {
			AllExpertiseFields.value = resp.data;
		});
	};
	onMounted(() => {
		getAllExpertiseFields();
	});
	const add = () => {
		console.log("新增的id", form.value.id);
		if (form.value.id.length === 0) {
			axios.post('/consultant', {
				consultant: {
					address: form.value.address,
					gender:form.value.gender,
					certificateUrl: form.value.certificateUrl,
					email: form.value.email,
					avatarUrl: form.value.avatarUrl,
					levelId: form.value.levelId,
					name: form.value.name,
					mobile: form.value.mobile,
					position: form.value.position,
					introduction: form.value.introduction,
					id: form.value.id,
					del: "0"
				},
				fieldIds: form.value.fieldIds
			}).then((resp) => {
				console.log('触发新增请求', resp);
				if (resp.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			});
		} else {
			axios.put('consultant', {
				consultant: {
					address: form.value.address,
					gender:form.value.gender,
					certificateUrl: form.value.certificateUrl,
					email: form.value.email,
					avatarUrl: form.value.avatarUrl,
					levelId: form.value.levelId,
					name: form.value.name,
					mobile: form.value.mobile,
					position: form.value.position,
					introduction: form.value.introduction,
					id: form.value.id,
					del: "0"
				},
				fieldIds: form.value.fieldIds
			}).then((resp) => {
				console.log('触发修改请求', resp);
				if (resp.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			});
		}
	}
	const remove = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`consultant/${row.id}`).then((resp) => {
					console.log('删除后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error(resp.data || '删除失败')
					}
				}).finally(() => {
					query();
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	const removeAll = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请至少选择一项');
			return;
		}

		ElMessageBox.confirm(
			'此操作将永久删除该文件, 是否继续?',
			'Warning', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			// 转换为数字数组
			const idsToDelete = multipleSelection.value.map(id => Number(id));

			// 使用data传递请求体
			axios.delete('consultant', {
				data: idsToDelete,
				headers: {
					'Content-Type': 'application/json'
				}
			}).then(resp => {
				// 处理纯文本响应
				if (resp.code == 200) {
					ElMessage.success(resp.data || '删除成功');
				} else {
					ElMessage.error(resp.data || '删除失败');
				}
			}).catch(error => {
				ElMessage.error(`删除失败: ${error.response?.data || error.message}`);
			}).finally(() => {
				query();
			});
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			});
		});
	};


	onMounted(() => {
		query();
		getAllCounselorLevel();
	})
</script>
<style scoped>
	.counselorPostsOne {
		width: 78px;
		background-color: #ecf5ff;
		border: 1px solid #d9ecff;
		color: #44a0ff;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.counselorPostsTwo {
		width: 78px;
		background-color: #fef0f0;
		border: 1px solid #fde2e2;
		color: #f56d6d;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.spanTop {
		margin: 0 10px;
		color: #696a6e;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.bt1 {
		margin-top: 10px;
		margin-left: 10px;
	}

	.div1 {
		border-bottom: 1px solid #eeeeee;
		width: 100%;
		height: 30px;
		padding-top: 15px;
		padding-left: 15px;
	}

	.div2 {
		padding-top: 15px;
	}

	.el-table {
		margin-left: 10px;
	}

	.el-pagination {
		margin-top: 10px;
		margin-left: 10px;
	}
</style>